<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin:20px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" placeholder="输入手机号"/>
    </el-form-item>
    <el-form-item label="初始密码" prop="password">
      <el-switch v-model="form.password" active-text="默认为：dlb123456" disabled />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">创建</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { Message } from 'element-ui'
import { register } from '@/api/table'
import { isvalidPhone } from '@/utils/validate'

var checkPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号码'))
  } else if (!isvalidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

export default {
  data() {
    return {
      form: {
        username: '',
        password: true
      },
      rules: {
        username: [
          { required: true, trigger: 'blur', validator: checkPhone }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          register({
            username: this.form.username
          }).then(res => {
            Message({
              message: '创建成功',
              type: 'success',
              duration: 3 * 1000
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 310px;
    height: 178px;
    line-height: 190px;
    text-align: center;
  }
  .avatar {
    width: 310px;
    height: 190px;
    display: block;
  }
</style>
